package com.itheima.dfs.controller;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.enums.HttpCodeEnum;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.RequestContextUtil;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.feign.WmMaterialFeign;
import com.itheima.wemedia.pojo.WmMaterial;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.Collections;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima.dfs.controller
 */
@RestController
@RequestMapping("/dfs")
@Slf4j
@Api("文件操作")
public class FileController {

    @Resource
    private FastFileStorageClient client;

    @Resource
    private FdfsWebServer webServer;

    @Resource
    private WmMaterialFeign wmMaterialFeign;

    /**
     * 上传文件 到 fastdfs
     * 【注意】
     * 1. 参数类型MultipartFile
     * 2. 参数名称要与提交请求参数的名称要一致，严格区分大小写
     * 3. 可以不一致，则必须得使用@RequestParam注解, 取别名必须与请求参数一数，形参名就可以随意
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public ResultVo upload(MultipartFile multipartFile){
        //1. 获取请求的来源
        String from = RequestContextUtil.getHeader(SystemConstants.USER_HEADER_FROM);
        if (StringUtils.isEmpty(from)){
            // from是空值，说明没有经过网关，非法请求
            return ResultVo.error(HttpCodeEnum.NO_OPERATOR_AUTH);
        }

        // inputStream 文件的输入流
        InputStream is = null;
        try {
            is = multipartFile.getInputStream();
            //fileSize 文件的大小
            long size = multipartFile.getSize();
            //fileName 文件扩展名  后缀名
            String originalFilename = multipartFile.getOriginalFilename();
            String ext = StringUtils.getFilenameExtension(originalFilename);
            //2. 上传到fastdfs上
            StorePath storePath = client.uploadFile(is, size, ext, null);
            //3. 返回完整的路径给前端，回显
            String fileId = storePath.getFullPath();
            log.info("上传了文件：{}",fileId);
            String fullPath = webServer.getWebServerUrl() + fileId;

            // 判断是否需要远程调用自媒体添加记录
            if (SystemConstants.WEMEDIA_PIC.equals(from)){
                addWmMaterial(fileId);
            }

            // 前端的格式要求：{url：全路径}
            // singletonMap: 这个map只有一个key
            return ResultVo.ok(Collections.singletonMap("url",fullPath));
        } catch (IOException e) {
            log.error("上传文件失败",e);
        }
        return ResultVo.error();
    }

    /**
     *添加素材
     * @param fileId
     */
    private void addWmMaterial(String fileId) {
        // 构建素材对象
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUrl(fileId);
        wmMaterial.setIsCollection(0);
        wmMaterial.setType(0);
        wmMaterial.setCreatedTime(LocalDateTime.now());
        wmMaterial.setUserId(RequestContextUtil.getUserId());
        // 远程调用
        ResultVo addResult = wmMaterialFeign.add(wmMaterial);
        if (!addResult.isSuccess()) {
            throw new LeadNewsException("上传素材失败！");
        }
    }
}
